from IPython.display import display
from PIL import Image
from openai import OpenAI
import base64
import os

# 设置图像路径和提示词
image_path = "C:/Users/zhoujiaqing/Desktop/302/用QWen3进行OCR/5d8933add5f08a5933965bef43936d63.png"
prompt = "按照以下格式提取键值信息：{\"company\": \"\", \"date\": \"\", \"address\": \"\", \"total\": \"\"}"

# 显示图像
image = Image.open(image_path)
display(image.resize((1304,2180)))

# 图像编码函数
def encode_image(img_path):
    with open(img_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

# 使用基于API的方法进行OCR
# 请确保从阿里云百炼平台获取有效的API密钥：https://bailian.console.alibabacloud.com/?apiKey=1
# 并替换下面的API密钥
api_key = os.environ.get('DASHSCOPE_API_KEY', 'sk-3fe722ea8cd249beb3bf3da52099484b')

if api_key.startswith('sk-请替换'):
    print("警告：请替换为有效的API密钥！")
    print("获取地址：https://bailian.console.alibabacloud.com/?apiKey=1")

# 创建OpenAI客户端
client = OpenAI(
    api_key="sk-3fe722ea8cd249beb3bf3da52099484b",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    
)

# 准备消息和图像数据
base64_image = encode_image(image_path)
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
            },
            {"type": "text", "text": prompt},
        ],
    }
]

# 调用API进行OCR
try:
    completion = client.chat.completions.create(
        model="qwen3-vl-235b-a22b-instruct",
        messages=messages,
    )
    # 输出识别结果
    print("OCR识别结果：")
    print(completion.choices[0].message.content)
except Exception as e:
    print(f"API调用失败：{e}")
    print("请确认您的API密钥是否有效，并确保您的账户有足够的额度。")